package cn.iocoder.yudao.module.pay.wallet.controller.admin;

import cn.iocoder.yudao.framework.business.basic.pojo.vo.UserSimpleVO;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.api.member.user.MemberUserApi;
import cn.iocoder.yudao.module.api.pay.wallet.enums.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.wallet.convert.PayWalletConvert;
import cn.iocoder.yudao.module.pay.wallet.dal.dataobject.PayWalletDO;
import cn.iocoder.yudao.module.pay.wallet.service.PayWalletService;
import cn.iocoder.yudao.module.pay.wallet.vo.PayWalletPageReqVO;
import cn.iocoder.yudao.module.pay.wallet.vo.PayWalletRespVO;
import cn.iocoder.yudao.module.pay.wallet.vo.PayWalletUpdateBalanceReqVO;
import cn.iocoder.yudao.module.pay.wallet.vo.PayWalletUserReqVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.enums.UserTypeEnum.MEMBER;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.api.pay.ErrorCodeConstants.WALLET_NOT_FOUND;

@Tag(name = "管理后台 - 用户钱包")
@RestController
@RequestMapping("/pay/wallet")
@Validated
@Slf4j
public class PayWalletController {

    @Resource
    private PayWalletService payWalletService;

    @Resource
    private MemberUserApi memberUserApi;

    @GetMapping("/get")
    @PreAuthorize("@ss.hasPermission('pay:wallet:query')")
    @Operation(summary = "获得用户钱包明细")
    public CommonResult<PayWalletRespVO> getWallet(PayWalletUserReqVO reqVO) {
        PayWalletDO wallet = payWalletService.getOrCreateWallet(reqVO.getUserId(), MEMBER.getValue());
        return success(PayWalletConvert.INSTANCE.convert02(wallet));
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户钱包分页")
    @PreAuthorize("@ss.hasPermission('pay:wallet:query')")
    public CommonResult<PageResult<PayWalletRespVO>> getWalletPage(@Valid PayWalletPageReqVO pageVO) {
        PageResult<PayWalletDO> pageResult = payWalletService.getWalletPage(pageVO);
        PageResult<PayWalletRespVO> data = PayWalletConvert.INSTANCE.convertPage(pageResult);
        toVoList(data.getList());
        return success(data);
    }

    private void toVoList(List<PayWalletRespVO> list) {
        Set<Long> userIds = list.stream().map(PayWalletRespVO::getUserId).collect(Collectors.toSet());
        Map<Long, UserSimpleVO> userMap = memberUserApi.getUserSimpleMap(userIds);
        list.forEach(vo -> {
            UserSimpleVO user = userMap.get(vo.getUserId());
            if (user != null) {
                vo.setUserAvatar(user.getAvatar());
                vo.setUserNickname(user.getNickname());
            } else {
                vo.setUserAvatar(UserSimpleVO.ANONYMOUS.getAvatar());
                vo.setUserNickname(UserSimpleVO.ANONYMOUS.getNickname());
            }
        });
    }

    @PutMapping("/update-balance")
    @Operation(summary = "更新前台用户余额")
    @PreAuthorize("@ss.hasPermission('pay:wallet:update-balance')")
    public CommonResult<Boolean> updateWalletBalance(@Valid @RequestBody PayWalletUpdateBalanceReqVO updateReqVO) {
        // 获得用户钱包
        PayWalletDO wallet = payWalletService.getOrCreateWallet(updateReqVO.getUserId(), MEMBER.getValue());
        if (wallet == null) {
            log.error("[updateWalletBalance]，updateReqVO({}) 用户钱包不存在.", updateReqVO);
            throw exception(WALLET_NOT_FOUND);
        }

        if (updateReqVO.getBalance() == null || updateReqVO.getBalance() == 0) {
            return success(false);
        }
        // 更新钱包余额
        if (updateReqVO.getBalance() < 0) {
            payWalletService.reduceWalletBalance(wallet.getId(), String.valueOf(updateReqVO.getUserId()), PayWalletBizTypeEnum.UPDATE_BALANCE, updateReqVO.getBalance());
        } else {
            payWalletService.addWalletBalance(wallet.getId(), String.valueOf(updateReqVO.getUserId()), PayWalletBizTypeEnum.UPDATE_BALANCE, updateReqVO.getBalance());
        }
        return success(true);
    }

}
